import { memo, FC, useRef, useEffect } from 'react'
import { Modal, Form, Input, Select, message } from 'antd'
import type { FormInstance } from 'antd'
import { RoleListType, RoleModelState, connect, Dispatch } from 'umi'
const { Option } = Select
const { TextArea } = Input
interface IProps {
  visible: boolean
  hide: () => void
  record: RoleListType | undefined
  update: () => void
  dispatch: Dispatch
}
interface FormValues {
  [name: string]: any
}
const EditRole: FC<IProps> = ({ visible, hide, record, dispatch, update }) => {
  const formRef = useRef<FormInstance>(null)
  const handleOk = () => {
    formRef.current?.submit()
  }
  const handleCancel = () => {
    hide()
    formRef.current?.resetFields()
  }
  const onFinish = (values: FormValues) => {
    dispatch({
      type: 'roleModel/function_saveRoleInfo',
      payload: { code: record!.code, ...values },
      callback: (response) => {
        if (response.code === 200) {
          message.success('编辑成功')
          handleCancel()
          update()
        }
      }
    })
  }
  useEffect(() => {
    if (visible) {
      formRef.current?.setFieldsValue(record)
    }
  }, [visible])
  return (
    <>
      <Modal
        title="编辑角色"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="40%"
        okText="确认"
        cancelText="取消"
        maskClosable={false}
      >
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          autoComplete="off"
          initialValues={{ status: '1' }}
          ref={formRef}
          onFinish={onFinish}
        >
          <Form.Item
            label="角色名称"
            name="name"
            rules={[{ required: true, message: '请输入角色名称!' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item label="备注信息" name="desc">
            <TextArea placeholder="请输入备注信息" />
          </Form.Item>
          <Form.Item
            label="角色状态"
            name="status"
            rules={[{ required: true, message: '请输入角色状态!' }]}
          >
            <Select placeholder="请选择角色状态">
              <Option value={'0'}>禁用</Option>
              <Option value={'1'}>启用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

const mapStateToProps = ({ roleModel }: { roleModel: RoleModelState }) => {
  return {
    roleModel
  }
}

export default connect(mapStateToProps)(memo(EditRole))
